﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;

namespace AcademicAudit_JoelShuman
{
	public static class DefaultCourseList
	{
		public static List<Course> DEFAULTCOURSELIST { get; set; }
	}
	public static class CSVParser
	{
		public static List<Course> ParseCourseCSV( String fileName )
		{
			//Read a comma delimited string from a file   
			StreamReader sReader = null;
			FileStream fs = null;
			List<Course> listOfCourses = new List<Course>();

			try
			{
				fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
				sReader = new StreamReader(fs);
				String line;
				char[] trimChars = { '\n', 'r', ' ' };
				CourseType currentType = CourseType.CORE;
				int courseID = 1;
				while ((line = sReader.ReadLine()) != null)  //Read comma delimited string from file
				{
					Course tempCourse = new Course();
					// If the line has no commas, and then it is a new CourseType.
					if( ! line.Contains( ",") )
					{

						switch( line.TrimEnd( trimChars))
						{
							case "Core":
								currentType = CourseType.CORE;
								break;
							case "GenEd":
								currentType = CourseType.GENED;
								break;
							case "Electives":
								currentType = CourseType.ELECTIVE;
								break;
							default:
								currentType = CourseType.ELECTIVE;
								break;
						}
						continue;
					}

					//Parse and display each value in the comma delimited string     
					String[] resultArray = line.Split(',');

					// If the array size is 2, get the total credits.
					if( resultArray.Length == 2 )
					{
						continue;
					}

					// If 3, New Course, then Course#, Course Name, Credits
					if( resultArray.Length == 3 )
					{
						tempCourse.m_CourseNumber = resultArray[0];
						tempCourse.m_CourseName = resultArray[1];
						tempCourse.m_Credits = Convert.ToInt32(resultArray[2]);

						// Generate unique courseID; 
						tempCourse.m_CourseID = courseID;
						courseID++;
						/*
						FileStream tempFs = new FileStream("../../DataFiles/CourseID.txt", FileMode.Open, FileAccess.Read);
						StreamReader tempReader = new StreamReader(tempFs);
						String tempLine = tempReader.ReadLine().TrimEnd(trimChars);
						tempReader.Close();
						tempFs.Close();
						
						int nextIdAvailable = Convert.ToInt32(tempLine);
						tempCourse.m_CourseID = nextIdAvailable;

						tempFs = new FileStream("../../DataFiles/CourseID.txt", FileMode.Truncate, FileAccess.Write);
						StreamWriter tempWriter = new StreamWriter(tempFs);
						tempWriter.WriteLine(++nextIdAvailable);
						tempWriter.Close();
						tempFs.Close();
						*/
						// Set default value for Semester, year, grade, and status.
						tempCourse.m_Semester = Semester.NOTSET;
						tempCourse.m_year = 0;
						tempCourse.m_CourseGrade = Grade.UNKNOWN;
						tempCourse.m_CourseStatus = Status.I;

						// Set the course type
						tempCourse.m_CourseType = currentType;

						listOfCourses.Add(tempCourse);
					}

				}
				sReader.Close();

				return listOfCourses;
			}
			catch (Exception e)
            {
                MessageBox.Show(e.Message, "CSV Default Course List Parse Error");
				return null;
			}
			finally
			{
				if (sReader != null) sReader.Close();
				if (fs != null) fs.Close();
			}
		}

		public static StudentRecord ReadStudentCSV(String fileName)
		{
			StreamReader sReader = null;
			FileStream fs = null;
			List<Course> listOfCourses = new List<Course>();
			StudentRecord theStudent = new StudentRecord();

			try
			{
				fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
				sReader = new StreamReader(fs);
				String line;
				char[] trimChars = { '\n', 'r', ' ' };
				// StudentInfo
				// m_StudentID,m_FirstName,m_LastName,m_FullName,m_FileName,m_CoreCompletionPercentage,m_GenEdCompletionPercentage,m_GPA
				// Courses
				// m_CourseID,m_CourseNumber,m_CourseName,m_Credits,m_Semester,m_year,m_CourseType,m_CourseGrade,m_CourseStatus
				String currentSection = "StudentInfo";
				while ((line = sReader.ReadLine()) != null)  //Read comma delimited string from file
				{
					Course tempCourse = new Course();
					// If the line has no commas, and then it is a new CourseType.
					if (!line.Contains(","))
					{
						currentSection = line.TrimEnd(trimChars);
						continue;
					}

					//Parse and display each value in the comma delimited string     
					String[] resultArray = line.Split(',');
					
					if( currentSection == "StudentInfo")
					{
						theStudent.m_StudentID = resultArray[0];
						theStudent.m_FirstName = resultArray[1];
						theStudent.m_LastName = resultArray[2];
						theStudent.m_FullName = resultArray[3];
						theStudent.m_FileName = resultArray[4];
						theStudent.m_CoreCompletionPercentage  = Convert.ToDouble(resultArray[5]);
						theStudent.m_GenEdCompletionPercentage = Convert.ToDouble(resultArray[6]);
						theStudent.m_GPA = Convert.ToDouble(resultArray[7].TrimEnd(trimChars));
						continue;
					}

					// m_CourseID,m_CourseNumber,m_CourseName,m_Credits,m_Semester,m_year,m_CourseType,m_CourseGrade,m_CourseStatus
					if( currentSection == "Courses" )
					{
						tempCourse.m_CourseID = Convert.ToInt32(resultArray[0]);
						tempCourse.m_CourseNumber = resultArray[1];
						tempCourse.m_CourseName = resultArray[2];
						tempCourse.m_Credits = Convert.ToInt32(resultArray[3]);
						tempCourse.m_Semester = (Semester)Enum.Parse(typeof(Semester),resultArray[4]);
						tempCourse.m_year = Convert.ToInt32(resultArray[5]);
						tempCourse.m_CourseType = (CourseType)Enum.Parse(typeof(CourseType),resultArray[6]);
						tempCourse.m_CourseGrade = (Grade)Enum.Parse(typeof(Grade),resultArray[7]);
						tempCourse.m_CourseStatus = (Status)Enum.Parse(typeof(Status), resultArray[8].TrimEnd(trimChars));
						listOfCourses.Add(tempCourse);
						continue;
					}
				}
				sReader.Close();
				theStudent.m_CourseList = listOfCourses;
			}
			catch (Exception e)
            {
                MessageBox.Show(e.Message+"\n"+e.StackTrace, "CSV Student File Read Error");
				return null;
			}
			finally
			{
				if (sReader != null) sReader.Close();
				if (fs != null) fs.Close();
			}
			return theStudent;
		}

		public static bool WriteStudentCSV(StudentRecord theStudent)
		{
			StreamWriter sWriter = null;
			FileStream fs = null;

			try
			{
				fs = new FileStream(MainRecords.STUDENTDIR + theStudent.m_FileName + ".csv", FileMode.Create, FileAccess.Write);
				sWriter = new StreamWriter(fs);
				// StudentInfo
				// m_StudentID,m_FirstName,m_LastName,m_FullName,m_FileName,m_CoreCompletionPercentage,m_GenEdCompletionPercentage,m_GPA
				// Courses
				// m_CourseID,m_CourseNumber,m_CourseName,m_Credits,m_Semester,m_year,m_CourseType,m_CourseGrade,m_CourseStatus
				String fileContents = "StudentInfo\n";
				//sWriter.WriteLine("StudentInfo");
				//sWriter.Flush();

                String newLine;
                newLine = theStudent.m_StudentID + ",";
                newLine += theStudent.m_FirstName + ",";
                newLine += theStudent.m_LastName + ",";
                newLine += theStudent.m_FullName + ",";
                newLine += theStudent.m_FileName + ",";
                newLine += theStudent.m_CoreCompletionPercentage.ToString() + ",";
                newLine += theStudent.m_GenEdCompletionPercentage.ToString() + ",";
                newLine += theStudent.m_GPA.ToString();

				fileContents += newLine + "\n";
				//sWriter.WriteLine(newLine);
				//.Flush();

				fileContents += "Courses\n";
				//sWriter.WriteLine("Courses");
				//sWriter.Flush();

                foreach( Course tempCourse in theStudent.m_CourseList)
                {
					String aLine;
					aLine = tempCourse.m_CourseID.ToString() + ",";
					aLine += tempCourse.m_CourseNumber + ",";
					aLine += tempCourse.m_CourseName + ",";
					aLine += tempCourse.m_Credits.ToString() + ",";
					aLine += tempCourse.m_Semester.ToString() + ",";
					aLine += tempCourse.m_year.ToString() + ",";
					aLine += tempCourse.m_CourseType.ToString() + ",";
					aLine += tempCourse.m_CourseGrade.ToString() + ",";
					aLine += tempCourse.m_CourseStatus.ToString() + ",";

					fileContents += aLine + "\n";
					//sWriter.WriteLine(newLine);
					//sWriter.Flush();
				}
				sWriter.WriteLine(fileContents);
				sWriter.Flush();
			}
			catch (Exception e)
			{
                MessageBox.Show(e.Message, "CSV Student File Write Error");
                return false;
			}
			finally
			{
				if (sWriter != null) sWriter.Close();
				if (fs != null) fs.Close();
			}
            return true;
		}
	}
}
